<?php

/**
 * Helper functions.
 * 
 * @author Volker Kueffel <volker.kueffel@gmail.com>
 * @version $Id:Utils.class.php 18 2009-01-05 02:18:30Z volker.kueffel $
 */
class Utils {

	private static $ldapFields=array('givenname','sn','cn', 'mozillanickname', 'mail','mozillasecondemail','nsaImid', 'telephonenumber', 'homephone', 'fax', 'pager','mobile'
							,'mozillahomestreet', 'mozillahomestreet2', 'mozillahomelocalityname', 'mozillahomestate', 'mozillahomepostalcode', 'mozillahomecountryname','street'
							,'mozillaworkstreet2', 'l', 'st', 'postalcode', 'c', 'title', 'department', 'company', 'mozillaworkurl', 'mozillahomeurl', 'mozillacustom1', 'mozillacustom2'
							,'mozillacustom3', 'mozillacustom4', 'description');
	
	/**
	 * Create StdClass out of array.
	 * 
	 * Field names are built using the array keys,
	 * values are the array values. Numeric keys are
	 * ignored.
	 * 
	 * @param array $input the array to convert
	 * 
	 * @return StdClass object created from array
	 */
	public static function array2Object($input) {
   		$result=new StdClass();
   		//print_r($input);
   		foreach ($input as $key=>$value) {
 			if (!is_numeric($key)) {
 				// seems the key is always lowercase in the response :-(
 				// make sure this still works if that ever changes...
 				$key=StrToLower($key);
 				$result->$key=$value;
 			}  			
   		}
   		return $result;
	}
	
	
	/**
	 * Extract LDAP specific fields from array, usually request array.
	 * 
	 * @param array $input array to extract fields from
	 * 
	 * 	@return array array to be used with ldap_* functions
	 */
	public static function request2LdapArray($input) {
		$result=array();
 		if ($input && is_array($input)) {
	 		foreach (self::$ldapFields as $fieldName) {
				if (array_key_exists($fieldName,$input) && $input[$fieldName]) {
					$result[$fieldName]=$input[$fieldName];
				}
			} 
 		}	
		return $result;
	}
	
	
	
	
	/**
	 * Extract parent DN of given DN
	 * 
	 * @param string $dn DN to extract parent from
	 * 
	 * @return string parent DN or empty string if no parent is found
	 */
	public static function getParentDN($dn) {
		$dn=preg_replace('/\s*,\s*/',',',$dn);
		$parts=preg_split('/,/',$dn);
		$parent=null;
		if (is_array($parts) && count($parts)>1) {
			array_shift($parts);
			$parent=join(',',$parts);
		}
		return $parent;
	}
		
}
?>